import request from "@/utils/request";
import type { ApiResponse, PageResult } from "@/types";

// 悄悄话相关类型
export interface WhisperCreateRequest {
  recipientType: "username" | "code"; // 接收者类型：username=用户名，code=暗号
  recipientValue: string; // 接收者值：用户名或暗号
  content: string; // 悄悄话内容
  isAnonymous: boolean; // 是否匿名发送
  senderName?: string; // 发送者昵称（匿名时使用）
}

export interface WhisperDTO {
  id: number;
  content: string;
  senderName?: string;
  recipientType: "username" | "code";
  recipientValue: string;
  isAnonymous: boolean;
  isRead: boolean;
  createdAt: string;
  sender?: {
    id: number;
    username: string;
    nickname?: string;
    avatar?: string;
  };
}

export interface WhisperSearchRequest {
  keyword: string;
  searchType?: "all" | "username" | "code";
  page?: number;
  size?: number;
}

export interface WhisperAdvancedSearchRequest {
  targetKeyword?: string;
  contentKeyword?: string;
  page?: number;
  size?: number;
}

export interface WhisperSettingsDTO {
  id?: number;
  allowAnonymous: boolean;
  enabled: boolean;
  createdAt?: string;
  updatedAt?: string;
}

/**
 * 发送悄悄话
 */
export function sendWhisper(data: WhisperCreateRequest): Promise<WhisperDTO> {
  return request({
    url: "/whispers",
    method: "post",
    data,
  });
}

/**
 * 获取收到的悄悄话
 */
export function getReceivedWhispers(page = 1, size = 10): Promise<PageResult<WhisperDTO>> {
  return request({
    url: "/whispers/received",
    method: "get",
    params: { page, size },
  });
}

/**
 * 获取发送的悄悄话
 */
export function getSentWhispers(page = 1, size = 10): Promise<PageResult<WhisperDTO>> {
  return request({
    url: "/whispers/sent",
    method: "get",
    params: { page, size },
  });
}

/**
 * 通过暗号获取悄悄话
 */
export function getWhispersByCode(
  code: string,
  page = 1,
  size = 10
): Promise<PageResult<WhisperDTO>> {
  return request({
    url: `/whispers/code/${encodeURIComponent(code)}`,
    method: "get",
    params: { page, size },
  });
}

/**
 * 搜索悄悄话
 */
export function searchWhispers(params: WhisperSearchRequest): Promise<PageResult<WhisperDTO>> {
  return request({
    url: "/whispers/search",
    method: "get",
    params,
  });
}

/**
 * 高级搜索悄悄话
 */
export function advancedSearchWhispers(
  params: WhisperAdvancedSearchRequest
): Promise<PageResult<WhisperDTO>> {
  return request({
    url: "/whispers/search/advanced",
    method: "get",
    params,
  });
}

/**
 * 删除悄悄话
 */
export function deleteWhisper(whisperId: number): Promise<ApiResponse> {
  return request({
    url: `/whispers/${whisperId}`,
    method: "delete",
  });
}

/**
 * 获取悄悄话设置
 */
export function getWhisperSettings(): Promise<WhisperSettingsDTO> {
  return request({
    url: "/whispers/settings",
    method: "get",
  });
}

/**
 * 更新悄悄话设置
 */
export function updateWhisperSettings(data: WhisperSettingsDTO): Promise<WhisperSettingsDTO> {
  return request({
    url: "/whispers/settings",
    method: "put",
    data,
  });
}
